import type { Module, ActionContext } from 'vuex'
import type { AxiosResponse } from 'axios'
import type { manholeState } from './typings'
import {
  manholeListGet,
  manholeRemovePost,
  manholeExportGet,
  manholeImportExcelGet,
  manholeModelGet,
  manholeViewGet,
  manholeAddPost,
  manholeUpdatePost,
  manholeExportTemplateGet
} from '~/api/asset/manhole'
import { DownloadAttachment } from '~/utils/util'

const manhole: Module<manholeState, manholeState> = {
  namespaced: true,
  state: {
    manholeModelOpt: []
  },
  getters: {
    manholeModelOpt: (state) => state.manholeModelOpt
  },
  mutations: {
    SET_MANHOLE_MODEL: (state, payload) => {
      state.manholeModelOpt = payload
    }
  },
  actions: {
    // 井盖-型号
    async ManholeModelGet<S, T>({ commit }: ActionContext<S, T>) {
      return await manholeModelGet({}).then((res: AxiosResponse) => {
        commit('SET_MANHOLE_MODEL', res?.data?.data || [])
        return res?.data
      })
    },
    // 井盖-列表
    async ManholeListGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeListGet<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 井盖-删除
    async ManholeRemovePost<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeRemovePost<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 井盖-导出
    async ManholeExportGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeExportGet<T>(params).then((res: AxiosResponse) => {
        const contentDisposition = res?.headers?.['content-disposition']
        if (contentDisposition && res.data) {
          DownloadAttachment(decodeURI(contentDisposition.substring(20)), res.data)
        }
        return res.data
      })
    },
    // 井盖-模版下载
    async ManholeExportTemplateGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeExportTemplateGet<T>(params).then((res: AxiosResponse) => {
        const contentDisposition = res?.headers?.['content-disposition']
        if (contentDisposition && res.data) {
          DownloadAttachment(decodeURI(contentDisposition.substring(20)), res.data)
        }
        return res.data
      })
    },
    // 井盖-导入
    async ManholeImportExcelGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeImportExcelGet<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 井盖-详情
    async ManholeViewGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeViewGet<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 井盖-新增
    async ManholeAddPost<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeAddPost<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 井盖-修改
    async ManholeUpdatePost<S, T>(_: ActionContext<S, T>, params: T) {
      return await manholeUpdatePost<T>(params).then((res: AxiosResponse) => res?.data)
    }
  }
}

export default manhole
